﻿using System;
using System.Security.Principal;
using System.Web.Mvc;

namespace Songhay.Web.Mvc.ModelBinders
{
    /// <summary>
    /// Defines a Model Binder for <see cref="System.Security.Principal.IPrincipal"/>
    /// </summary>
    public class IPrincipalModelBinder : IModelBinder
    {
        /// <summary>
        /// Registers this instance.
        /// </summary>
        public static void Register()
        {
            System.Web.Mvc.ModelBinders.Binders[typeof(IPrincipal)] = new IPrincipalModelBinder();
        }

        /// <summary>
        /// Binds the model to a value.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>The bounded value.</returns>
        /// <remarks>
        /// Based on
        /// “<a href="http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx">IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing</a>”
        /// by Scott Hanselman.
        /// </remarks>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if(controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext", "The Controller Context is null.");
            }
            if(bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext", "The Binding Context is null.");
            }
            IPrincipal p = controllerContext.HttpContext.User;
            return p;
        }
    }
}
